package com.nikmesoft.android.referendumfriend.adapters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import com.nikmesoft.android.referendumfriend.models.ItemHobies;
import com.nikmesoft.android.referendumfriend.models.MyGroupImage;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.person;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;

public class Group_adapter extends ArrayAdapter<person> {
	private int resourceID;
	final public List<person> its;
	public WSLoader loader;
	private ProgressDialog dialog;
	person item;
	ArrayList<String> id = new ArrayList<String>();

	public Group_adapter(Context context, int resourceID, List<person> objects,
			ArrayList<String> id) {
		super(context, resourceID, objects);
		this.resourceID = resourceID;
		its = objects;
		dialog = new ProgressDialog(context);
		dialog.setMessage("Loading...Please wait...");
		this.id = id;
	}

	static class ViewHolder {
		protected ImageView img;

	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		person person = its.get(position);
		View row = convertView;

		// if (row == null) {
		LayoutInflater inflater;
		inflater = (LayoutInflater) getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		row = inflater.inflate(this.resourceID, null);
		final ViewHolder vh = new ViewHolder();
		vh.img = (ImageView) row.findViewById(R.id.imageDelete);
		vh.img.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
						getContext());
				myAlertDialog.setTitle("Waring!");
				myAlertDialog.setMessage("Are you delete?");
				myAlertDialog.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								item = (person) vh.img.getTag();
								if (loader == null
										|| loader.isCancelled()
										|| loader.getStatus() == Status.FINISHED) {
									loader = new WSLoader();
									loader.execute(String
											.valueOf(LoginHandler.result
													.getId()),
											id.get(position), "2");
								}
								if (position != id.size() - 1) {
									int i = position;
									while (i != id.size() - 1) {
										id.set(i, id.get(i+1));
										i++;
									}
								}
							}
						});
				myAlertDialog.setNegativeButton("No",
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								// do something when the Cancel button is
								// clicked
							}
						});
				myAlertDialog.show();
			}

		});
		vh.img.setTag(its.get(position));

		// } else {
		// // row = convertView;
		// // ((ViewHolder)row.getTag()).img.setTag(its.get(position));
		// }

		TextView tvName = (TextView) row.findViewById(R.id.tvName);
//		TextView tvCount = (TextView) row.findViewById(R.id.tvCount);
		ImageView image_ic = (ImageView) row.findViewById(R.id.image);
		image_ic.setImageBitmap(MyGroupImage.ar_bitmap.get(position));

//		tvCount.setTag(person);
		// TextView tvStt = (TextView) row.findViewById(R.id.tv3);

		tvName.setText(person.getName());
		return row;

	}

	private String callWS(String name1, String name2, String name3) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<addRemoveHobby soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<AddRemoveHobbyRequest xsi:type=\"rdf:AddRemoveHobbyRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"
				+ name1
				+ "</id_user>"
				+ "<id_hobby xsi:type=\"xsd:int\">"
				+ name2
				+ "</id_hobby>"
				+ "<action xsi:type=\"xsd:int\">"
				+ name3
				+ "</action>"
				+ "</AddRemoveHobbyRequest>"
				+ "</addRemoveHobby>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	public class WSLoader extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			return callWS(params[0], params[1], params[2]);

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {

			super.onPostExecute(result);
			try {
				dialog.dismiss();
				its.remove(item);
				notifyDataSetChanged();
			} catch (Exception e) {
				dialog.dismiss();
			}

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}

}
